import { listRole,listAllRole,listPermsByRoleId,createRole,updateRole,deleteRole } from "@/pages/Setting/services/role";

export default {
  namespace: "role",

  state: {
    data: {
      list: [],
      pagination: {}
    }
  },

  effects: {
    *list({ payload }, { call, put }) {
      const response = yield call(listRole, payload);
      yield put({
        type: "save",
        payload: response
      });
    },
    *listPerms({ payload,callback }, { call, put }) {
      const response = yield call(listPermsByRoleId, payload);
      yield put({
        type: "saveCheckedPerms",
        payload: response
      });
      if (callback) callback(response);
    },
    *listAll({ payload }, { call, put }) {
      const response = yield call(listAllRole, payload);
      yield put({
        type: "saveAll",
        payload: response
      });
    },
    *create({ payload, callback }, { call, put }) {
      const response = yield call(createRole, payload);
      yield put({
        type: "save",
        payload: response
      });
      if (callback) callback();
    },
    *update({ payload, callback }, { call, put }) {
      const response = yield call(updateRole, payload);
      yield put({
        type: "save",
        payload: response
      });
      if (callback) callback();
    },
    *delete({ payload, callback }, { call, put }) {
      const response = yield call(deleteRole, payload);
      yield put({
        type: "save",
        payload: response
      });
      if (callback) callback();
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload.data
      };
    },
    saveAll(state, action) {
      return {
        ...state,
        allRoleData: action.payload.data
      };
    },
    saveCheckedPerms(state, action) {
      return {
        ...state,
        checkedPerms: action.payload.data
      };
    }
  }
};
